package com.yz.fanrenmianshi.utils;

import com.aliyun.oss.ClientBuilderConfiguration;
import com.aliyun.oss.OSS;
import com.aliyun.oss.OSSClientBuilder;
import com.aliyun.oss.common.comm.SignVersion;
import com.yz.fanrenmianshi.properties.AliyunOSSProperties;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.io.ByteArrayInputStream;
import java.time.LocalDate;
import java.time.format.DateTimeFormatter;
import java.util.UUID;

@Component
public class AliOssUtil {

    @Autowired
    private AliyunOSSProperties aliOssProperties;

    /**
     * 文件上传
     *
     * @param bytes
     * @param originalFilename
     * @return
     */
    public String upload(byte[] bytes, String originalFilename) throws Exception {
        // 从配置属性中获取OSS配置信息
        String endpoint = aliOssProperties.getEndpoint();
        String bucketName = aliOssProperties.getBucketName();
        String accessKeyId = aliOssProperties.getAccessKeyId();
        String accessKeySecret = aliOssProperties.getAccessKeySecret();

        // 生成文件路径和文件名
        String dir = LocalDate.now().format(DateTimeFormatter.ofPattern("yyyy/MM"));
        String fileExtension = "";
        int lastDotIndex = originalFilename.lastIndexOf(".");
        if (lastDotIndex != -1) {
            fileExtension = originalFilename.substring(lastDotIndex);
        }
        String newFileName = UUID.randomUUID() + fileExtension;
        String objectName = dir + "/" + newFileName;

        // 创建OSSClient实例
        ClientBuilderConfiguration clientBuilderConfiguration = new ClientBuilderConfiguration();
        clientBuilderConfiguration.setSignatureVersion(SignVersion.V4);

        OSS ossClient = new OSSClientBuilder().build(endpoint, accessKeyId, accessKeySecret);

        try {
            // 上传文件
            ossClient.putObject(bucketName, objectName, new ByteArrayInputStream(bytes));
        } finally {
            ossClient.shutdown();
        }

        // 返回文件的访问URL
        // 如果endpoint不包含协议头，添加https://
        String fullEndpoint = endpoint.startsWith("http") ? endpoint : "https://" + endpoint;
        String[] endpointParts = fullEndpoint.split("//");
        return endpointParts[0] + "//" + bucketName + "." + endpointParts[1] + "/" + objectName;
    }
}
